<?php

$server = new swoole_websocket_server("0.0.0.0", 9501);

$server->on('open', function (swoole_websocket_server $server, $request) {
    file_put_contents(__DIR__ . '/log.txt', $request->fd);
});

//$server->on('message', function (swoole_websocket_server $server, $frame) {
//    global $client;
//    $data = $frame->data;
//    $m = file_get_contents(__DIR__ . '/log.txt');
//    for ($i = 1; $i <= $m; $i++) {
//        echo PHP_EOL . '  I is  ' . $i . '  data  is: ' . $data . '  m = ' . $m;
//        $s = $server->push($i, $data);
//        var_dump($s);
//    }
//
//});

$server->on('message', function (swoole_websocket_server $server, $frame) {
    echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
    foreach ($server->connections as $fd) {
        $server->push($fd, "receive from {$frame->fd}:".$frame->data);
    }

//    $server->push($frame->fd, "receive from {$frame->fd}:".$frame->data);
});

$server->on('close', function ($ser, $fd) {
    echo "client {$fd} closed\n";
});


$server->on('request', function (swoole_http_request $request, swoole_http_response $response) {
    global $server;
     // 调用外部的server
    // $server->connections 遍历所有websocket连接用户的fd，给所有用户推送
    foreach ($server->connections as $fd) {
        $this->server->push($fd, $request->get['message']);
    }
});


$server->start();